
package jz.olap.unit;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import SoftFan.util.SysTsUnit;
import SoftFan.workflow.protocol.SoftFanUtilException;
import SoftFan.workflow.protocol.wfException;
import SoftFan.workflow.protocol.application.appContext;
import SoftFan.workflow.protocol.db.FactJDBCUnit;
import SoftFan.workflow.protocol.db.wf_Db_Connect;
import SoftFan.workflow.protocol.db.wf_Db_Exception;
import SoftFanJob.protocol.SoftFanJobException;

public class CalcGjzList {

	private List<Long>	gjzxxs	= new ArrayList<Long>();
	private long		lastTs;

	public void free() throws wf_Db_Exception {
		gjzxxs.clear();
	}

	public long getLastTs() {
		return lastTs;
	}

	protected void start(wf_Db_Connect connect) throws wf_Db_Exception {
		SysTsUnit tsUnit = new SysTsUnit();
		this.lastTs = tsUnit.loadTs(connect, "jzgjzcollectiondate");

	}

	protected void finish(wf_Db_Connect connect) throws wf_Db_Exception {
		SysTsUnit tsUnit = new SysTsUnit();
		tsUnit.saveTs(connect, "jzgjzcollectiondate", this.lastTs);
	}

	public void doExec(int maxRecord) throws SoftFanJobException, wfException, wf_Db_Exception, SoftFanUtilException {
		wf_Db_Connect extdb = appContext.getCurrentInstance().getJDBCConnect(jz.dbUnit.collectionData.collectionDataJDBCUnit.database);

		this.start(extdb);

		SoftFan.workflow.protocol.db.filter.expressionAnd exproot = SoftFan.workflow.protocol.db.filter.Expression.and();
		if (lastTs > 0) {
			exproot.add(SoftFan.workflow.protocol.db.filter.Expression.ge("collectiondate", new Date(lastTs)));
		} else {
			exproot.add(SoftFan.workflow.protocol.db.filter.Expression.isNotNull("collectiondate"));
		}
		
		try {
			PreparedStatement stmt = FactJDBCUnit.buildLoadSql(extdb, "cjrq", "collectiondata", exproot, "cjrq desc", 1);
			try {
				ResultSet rs = stmt.executeQuery();
				try {
					Timestamp timestamp = rs.getTimestamp(1);
					lastTs = timestamp.getTime();
				} finally {
					rs.close();
				}
			} finally {
				stmt.close();
			}
		} catch (SQLException e) {
			throw new wf_Db_Exception(e);
		}
		
		try {
			PreparedStatement stmt = FactJDBCUnit.buildLoadSqlDistinct(extdb, "gjzid", "collectiondata", exproot, "cjrq asc", -1);
			try {
				ResultSet rs = stmt.executeQuery();
				try {
					while (rs.next()) {
						gjzxxs.add(rs.getLong(1));
					}
				} finally {
					rs.close();
				}
			} finally {
				stmt.close();
			}
		} catch (SQLException e) {
			throw new wf_Db_Exception(e);
		}
		
		this.finish(extdb);
	}
}
